<template>
    <div id="userManagePage">
        <!-- 搜索表单 -->
        <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
            <a-form-item label="账号">
                <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" />
            </a-form-item>
            <a-form-item label="用户名">
                <a-input v-model:value="searchParams.userName" placeholder="输入用户名" />
            </a-form-item>
            <a-form-item>
                <a-button type="primary" html-type="submit">搜索</a-button>
            </a-form-item>
        </a-form>
        <a-divider />
        <!-- 表格 -->
    </div>

    <a-table :columns="columns" :data-source="data" :pagination="pagination" @change="doTableChange" class="table">
        <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'userAvatar'">
                <a-image :src="record.userAvatar" :width="120" />
            </template>
            <template v-else-if="column.dataIndex === 'userRole'">
                <div v-if="record.userRole === 'admin'">
                    <a-tag color="green">管理员</a-tag>
                </div>
                <div v-else>
                    <a-tag color="blue">普通用户</a-tag>
                </div>
            </template>
            <template v-else-if="column.dataIndex === 'createTime'">
                {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-else-if="column.key === 'action'">
                <a-space>
                    <a-button type="primary" @click="openEdit(record)">编辑</a-button>
                    <a-button danger @click="doDelete(record.id)">删除</a-button>
                </a-space>
            </template>
        </template>
    </a-table>

    <!-- 编辑弹窗 -->
    <a-modal :open="editVisible" title="编辑用户" @ok="doEdit" @cancel="handleEditCancel" destroyOnClose>
        <a-form ref="editFormRef" :model="editForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }"
            class="edit-form">
            <a-form-item label="用户名" name="userName" :rules="[{ required: true, message: '请输入用户名' }]">
                <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
            </a-form-item>
            <a-form-item label="头像" name="userAvatar">
                <a-input v-model:value="editForm.userAvatar" placeholder="请输入头像地址 URL" />
            </a-form-item>
            <a-form-item label="简介" name="userProfile">
                <a-textarea v-model:value="editForm.userProfile" :rows="3" placeholder="请输入个人简介" />
            </a-form-item>
            <a-form-item label="角色" name="userRole" :rules="[{ required: true, message: '请选择角色' }]">
                <a-select v-model:value="editForm.userRole" placeholder="请选择角色">
                    <a-select-option value="user">普通用户</a-select-option>
                    <a-select-option value="admin">管理员</a-select-option>
                </a-select>
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { listUserVoByPage, deleteUser, updateUser } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import type { FormInstance } from 'ant-design-vue'

const columns = [
    {
        title: 'id',
        dataIndex: 'id',
    },
    {
        title: '账号',
        dataIndex: 'userAccount',
    },
    {
        title: '用户名',
        dataIndex: 'userName',
    },
    {
        title: '头像',
        dataIndex: 'userAvatar',
    },
    {
        title: '简介',
        dataIndex: 'userProfile',
    },
    {
        title: '用户角色',
        dataIndex: 'userRole',
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
    },
    {
        title: '操作',
        key: 'action',
    },
]

// 页面加载时请求一次
onMounted(() => {
    fetchData()
})

// 数据
const data = ref<API.UserVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
    pageNum: 1,
    pageSize: 10,
})

// 获取数据
const fetchData = async () => {
    const res = await listUserVoByPage({
        ...searchParams,
    })
    if (res.data.data) {
        data.value = res.data.data.records ?? []
        total.value = res.data.data.totalRow ?? 0
    } else {
        message.error('获取数据失败，' + res.data.message)
    }
}

// 分页参数
const pagination = computed(() => {
    return {
        current: searchParams.pageNum ?? 1,
        pageSize: searchParams.pageSize ?? 10,
        total: total.value,
        showSizeChanger: true,
        showTotal: (total: number) => `共 ${total} 条`,
    }
})

// 表格变化处理
const doTableChange = (page: any) => {
    searchParams.pageNum = page.current
    searchParams.pageSize = page.pageSize
    fetchData()
}

// 获取数据
const doSearch = () => {
    // 重置页码
    searchParams.pageNum = 1
    fetchData()
}

// 删除数据
const doDelete = async (id: string) => {
    if (!id) {
        return
    }
    const res = await deleteUser({ id: Number(id) })
    if (res.data.code === 0) {
        message.success('删除成功')
        // 刷新数据
        fetchData()
    } else {
        message.error('删除失败')
    }
}

// 编辑弹窗可见性
const editVisible = ref(false)
// 编辑表单引用，用于校验
const editFormRef = ref<FormInstance>()
// 编辑表单数据
const editForm = reactive<API.UserUpdateRequest>({
    id: undefined as any,
    userName: '',
    userAvatar: '',
    userProfile: '',
    userRole: 'user',
})

/**
 * 打开编辑弹窗，并填充当前行数据
 * @param record 当前行用户数据
 */
const openEdit = (record: any) => {
    editForm.id = record.id
    editForm.userName = record.userName
    editForm.userAvatar = record.userAvatar
    editForm.userProfile = record.userProfile
    editForm.userRole = record.userRole
    editVisible.value = true
}

/**
 * 提交编辑数据
 */
const doEdit = async () => {
    if (!editForm.id) {
        message.error('缺少用户ID，无法更新')
        return
    }
    try {
        await editFormRef.value?.validate()
    } catch (e) {
        return
    }
    const res = await updateUser({
        id: editForm.id,
        userName: editForm.userName,
        userAvatar: editForm.userAvatar,
        userProfile: editForm.userProfile,
        userRole: editForm.userRole,
    })
    if (res.data.code === 0 && res.data.data) {
        message.success('更新成功')
        editVisible.value = false
        fetchData()
    } else {
        message.error('更新失败，' + res.data.message)
    }
}

/**
 * 关闭编辑弹窗
 */
const handleEditCancel = () => {
    editVisible.value = false
}

</script>

<style scoped>
#userManagePage {
    padding: 20px;
}

.search-form {
    margin-bottom: 16px;
    justify-content: center;
}

.table {
    width: 80%;
    margin: 0 auto;
}

.edit-form {
    margin-bottom: 16px;
}
</style>